<template>
  <el-tree-select
    v-model="selectedValues"
    :props="defaultProps"
    :data="dataSource"
    :multiple="multiple"
    :show-arrow="false"
    :show-checkbox="multiple"
    :expand-on-click-node="false"
    :offset="3"
    :fit-input-width="true"
    :multiple-limit="6"
    :filter-method="filterMethod"
    check-strictly
    value-key="id"
    default-expand-all
    filterable
    @change="change"
  />
</template>
<script setup lang="ts" generic="T extends ITreeEntity">
import type { ITreeEntity } from '@/types/entity';
import type { IResponseData } from '@/types/http';
import { translateDataToTree } from '@/utils/func';
import { dwHttp } from '@/utils/http';
import { onBeforeMount, ref, watch, type PropType } from 'vue';
import type { ITreeSelectorProp } from './tree-selector';
defineOptions({
  name: 'TreeSelector',
});

const props = defineProps({
  multiple: {
    type: Boolean,
    default: () => {
      return false;
    },
  },
  url: {
    type: String,
  },
  treeProps: {
    type: Object as PropType<ITreeSelectorProp>,
    default: () => {
      return { label: 'teamName', value: 'id', children: 'children' };
    },
  },
});
const multiple = props.multiple;

const dataSource = ref<T[]>([]);
const reload = () => {
  dwHttp({
    method: 'get',
    url: props.url,
    isSuccessTip: false,
  }).then((res: unknown) => {
    const { data } = res as IResponseData<T>;
    const treeData = data as unknown as ITreeEntity[];

    // eslint-disable-next-line @typescript-eslint/ban-ts-comment
    //@ts-ignore
    // treeData.push({ id: '0', parentId: '-1', teamName: '根節點' })
    //todo parentId转children格式
    const result = translateDataToTree(treeData);
    dataSource.value = result as unknown as T[];
  });
};
const defaultProps = props.treeProps;
const filterMethod = (value: string) => {
  console.log(value);
  // eslint-disable-next-line @typescript-eslint/ban-ts-comment
  //@ts-ignore
  data.value = [...data.value].filter((item) => item[props.treeProps.label].includes(value));
};
const emits = defineEmits(['change']);
onBeforeMount(async () => {
  await reload();
});
const change = (newValue: string | number | boolean | object | T[]) => {
  emits('change', newValue);
};

const selectedValues = defineModel<string | number | boolean | object | T[]>();
</script>
